package com.itheima.demo08;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;

public class MyRunnable implements Runnable {
    private String s;
    private CountDownLatch countDownLatch;

    public MyRunnable(String s, CountDownLatch countDownLatch) {
        this.s = s;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        InputStream in=null;
        FileOutputStream fos=null;
        try {
            URL url = new URL(s);
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            File file = new File(s);
            String name = file.getName();
            fos = new FileOutputStream("D:\\" + name);
            byte[] bytes = new byte[1024 * 8];
            int len;
            while ((len = in.read()) != -1) {
                fos.write(bytes, 0, len);
                fos.flush();
            }
            countDownLatch.countDown();

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                in.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
